//
//  OperanViewController.m
//  MIDI
//
//  Created by E.M.Game on 15/9/14.
//  Copyright (c) 2015年 QXSX. All rights reserved.
//

#import "OperanViewController.h"
#import "AppConfig.h"
#import "TiledPDFView.h"
#import "QuartzCore/QuartzCore.h"
#import "PdfViewCell.h"
#import "AFHTTPRequestOperation.h"


@interface OperanViewController ()<UITableViewDelegate , UITableViewDataSource>
@property (strong , nonatomic) NSString * mtitleName;
@property (weak, nonatomic) IBOutlet UITableView *myTabView;
@property  CGPDFDocumentRef pdf;
@property (strong , nonatomic) NSString * pdfUrl;   //pdf路径
@property (strong , nonatomic) NSString * fileName; //文件名
@property CGPDFPageRef page;
@property (assign , nonatomic) NSInteger pageCount;
@property (assign , nonatomic) CGFloat scale;

@end

@implementation OperanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mtitleName = @"曲谱详情";
    self.myTabView.dataSource = self;
    self.myTabView.delegate = self;
    self.pageCount = 0;
    self.scale = 1;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self configNavigationItem];
    
    if(self.pdfUrl == nil)
        return;
    NSURL *url = [NSURL URLWithString:self.pdfUrl];
    self.fileName = [self.pdfUrl lastPathComponent];
   
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //NSString *documentPath = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
    //NSString *path2 = [NSString stringWithFormat:@"%@%@" , documentPath , @"pdfCache" ];
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);                                                  NSString *docPath = [paths lastObject];
    NSLog([NSString stringWithFormat:@"docPath : %@" , docPath]);
    docPath = [docPath stringByAppendingString:@"/"];
     NSLog([NSString stringWithFormat:@"pdf filename : %@" , self.fileName]);
    NSString *fullFileName = [docPath stringByAppendingString:self.fileName];
    if([fileManager fileExistsAtPath:fullFileName])   //文件已经存在
    {
        [self onLoadPdfPath:fullFileName];
    }
    else
    {
//        if(![fileManager fileExistsAtPath:path2])
//        {
//            [fileManager createDirectoryAtPath:path2 withIntermediateDirectories:YES attributes:nil error:nil];
//            NSLog(@"begin Creat sucess");
//        }
//        if([fileManager fileExistsAtPath:path2])
//        {
//            NSLog(@"Creat sucess");
//        }
        NSURLRequest * request = [NSURLRequest requestWithURL:url];
        AFHTTPRequestOperation * operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        operation.inputStream = [NSInputStream inputStreamWithURL:url];
        operation.outputStream = [NSOutputStream outputStreamToFileAtPath:fullFileName append:NO];
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation , id responseObject)
         {
             [self onLoadPdfPath:fullFileName];
         }
                                         failure:^(AFHTTPRequestOperation *operation , NSError * error)
         {
             NSLog(@"download pdf error");
         }];
        [operation start];

    }
    //[self.myTabView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void) configNavigationItem
{
    [self.tabBarController configNavigationBarTintColor:UIColorRGBA(0, 0, 0, 1)];
    [self.navigationController.navigationBar setBarTintColor:MIDIColorOfNavigationBar];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationItem.title = self.mtitleName;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],UITextAttributeFont,nil]];
    
    [self configNavigationBackAction:^{
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
}

#pragma mark tableView datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)numberOfRowsInSection:(UITableView *)tabeleView
{
    if(self.pdf == nil)
    {
        return 1;
    }
    return self.pageCount;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(self.pdf == nil)
    {
        return 1;
    }
    return self.pageCount;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = self.view.frame.size.height;
    height = height * self.scale;
    return height;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * identifi = @"PdfViewCell";
    PdfViewCell *cell = nil;
    cell = [self.myTabView dequeueReusableCellWithIdentifier:identifi];
    if(cell == nil)
    {
        cell = [PdfViewCell loadFromNib];
    }
    NSInteger row = indexPath.row;
    if(self.pdf == nil)
        return cell;
    CGPDFPageRef mpage = CGPDFDocumentGetPage(self.pdf , row + 1);
    CGPDFPageRetain(mpage);
    // determine the size of the PDF page
    CGRect pageRect = CGPDFPageGetBoxRect(mpage, kCGPDFMediaBox);
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat pageScale1 = width/pageRect.size.width;
    CGFloat pageScale2 = height/pageRect.size.height;
    CGFloat pageScale = pageScale1 < pageScale2 ? pageScale1 : pageScale2;
    pageRect = CGRectMake(0, 0, pageRect.size.width * pageScale , pageRect.size.height * pageScale);
    
    if(cell.pdfView == nil)
        cell.pdfView = [[TiledPDFView alloc] initWithFrame:pageRect andScale:pageScale];
    [cell.pdfView setPage:mpage];
   [cell.myView addSubview: cell.pdfView];
    return cell;
}

#pragma mark - Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark UIScrollView delegate methods
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return nil;
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
   
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(double)scale
{
    
}


-(void)setPDFData : (id)data
{
    if(data != nil)
    {
        self.pdfUrl = data;
    }
}

-(void)onLoadPdfPath : (NSString *)pdfPath
{
   
    NSLog(@"pdfpath %@",pdfPath);
    NSURL *pdfpathurl = [[NSURL alloc] initFileURLWithPath:pdfPath];
    self.pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfpathurl);
    self.pageCount =  CGPDFDocumentGetNumberOfPages(self.pdf);
    [self.myTabView reloadData];
}


@end
